<template>
  <div>
    <el-form inline>
      <el-form-item label="关键字">
        <el-input v-model="keyword" type="text" />
      </el-form-item>

      <el-form-item>
        <el-button @click="search">搜索且打点</el-button>
      </el-form-item>
    </el-form>

    <el-form inline>
      <el-form-item label="起点">
        <el-input v-model="start" type="text" />
      </el-form-item>

      <el-form-item label="终点">
        <el-input v-model="end" type="text" />
      </el-form-item>

      <el-form-item>
        <el-button @click="handleClick">开始</el-button>
      </el-form-item>
    </el-form>

    <div ref="boxRef" class="box"></div>
  </div>
</template>

<script>
import axios from "axios";

export default {
  data() {
    return {
      keyword: "广东省深圳市宝安区西部硅谷",

      start: "广东省深圳市宝安区西部硅谷",
      end: "广东省深圳市宝安区黄田公园",
    };
  },

  mounted() {
    this.initMap();
  },

  methods: {
    // 初始化地图
    initMap() {
      // 创建地图实例
      this.map = new TMap.Map(this.$refs.boxRef, {
        center: new TMap.LatLng(22.626203, 113.83801),
        zoom: 16,
      });

      // 创建 MultiMarker 实例
      this.markerLayer = new TMap.MultiMarker({
        map: this.map,
      });

      // 创建 MultiPolyline 实例
      this.polylineLayer = new TMap.MultiPolyline({
        map: this.map,
      });
    },

    async search() {
      // 使用 地址解析 API
      const {
        result: { location },
      } = await axios
        .get("/tx/ws/geocoder/v1", {
          params: {
            address: encodeURIComponent(this.keyword),
            key: import.meta.env.VITE_MAP_KEY,
          },
        })
        .then((response) => response.data);

      console.log("location", location);

      // 根据 id 获取标记点的信息
      const marker = this.markerLayer.getGeometryById("keyword");
      if (!marker) {
        // 不存在，则 添加
        this.markerLayer.add([
          {
            id: "keyword", //点标记唯一标识，后续如果有删除、修改位置等操作，都需要此id
            position: new TMap.LatLng(location.lat, location.lng), //点标记坐标位置
          },
        ]);
      } else {
        console.log("marker", marker);
        // 存在，则 moveAlong
        this.markerLayer.moveAlong({
          keyword: {
            path: [
              new TMap.LatLng(marker.position.lat, marker.position.lng),
              new TMap.LatLng(location.lat, location.lng),
            ],
            duration: 2000, // 动画持续时间，单位 ms
          },
        });
      }

      // this.markerLayer.add([
      //   {
      //     id: "keyword" + new Date().getTime(), //点标记唯一标识，后续如果有删除、修改位置等操作，都需要此id
      //     position: new TMap.LatLng(location.lat, location.lng), //点标记坐标位置
      //   },
      // ]);
    },

    /**
     * 文字地址 转换成 经纬度坐标地址
     */
    addressToLocation(address) {
      return axios
        .get("/tx/ws/geocoder/v1", {
          params: {
            address,
            key: import.meta.env.VITE_MAP_KEY,
          },
        })
        .then((response) => {
          const data = response.data;
          const location = data.result.location;
          return `${location.lat},${location.lng}`;
        });
    },

    async handleClick() {
      // 1. 将 文字地址 转换成 经纬度坐标地址
      const [from, to] = await Promise.all([
        this.addressToLocation(this.start),
        this.addressToLocation(this.end),
      ]);
      console.log("== from", from);
      console.log("== to", to);

      // 2. 调用路径规划接口
      const {
        data: { result },
      } = await axios.get("/tx/ws/direction/v1/driving/", {
        params: {
          from,
          to,
          key: import.meta.env.VITE_MAP_KEY,
        },
      });

      // 3. 获取 polyline
      const polyline = result.routes[0].polyline;

      // 4. 对 polyline 做解压
      const coors = [polyline[0], polyline[1]];
      for (var i = 2; i < polyline.length; i++) {
        // debugger;
        coors[i] = coors[i - 2] + polyline[i] / 1000000;
      }

      // 5. 对 coors 做坐标点的转换
      const paths = [];
      for (var i = 0; i < coors.length; i += 2) {
        paths.push(new TMap.LatLng(coors[i], coors[i + 1]));
      }

      // 6. 连线
      this.polylineLayer.add({
        //新的折线添加到图层中
        id: "pl_1",
        paths,
      });

      console.log("=== paths", paths);
      console.log("=== coors", coors);
    },
  },
};
</script>

<style>
.box {
  width: 100%;
  height: 500px;
  border: 1px solid #000;
}
</style>
